<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 输入宽 -->
      <el-row type="flex" class="row-bg" :gutter="15">
        <el-col :span="6">
          <el-input
            placeholder="请输入内容"
            v-model="params.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-row>
            <el-button type="primary" @click="addDialogVisible = true"
              >添加用户</el-button
            >
          </el-row>
        </el-col>
      </el-row>
      <!-- 列表数据 -->
      <el-table :data="userlist" style="width: 100%" border stripe>
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeFn(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="edit(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="editremove(scope.row.id)"
            ></el-button>

            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                @click="setRoled(scope.row)"
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="params.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主题区域 -->
      <el-form
        :model="addFrom"
        status-icon
        :rules="rules"
        label-width="100px"
        ref="addFromRef"
      >
        <el-form-item label="用户名" prop="username">
          <!-- 用户名 -->
          <el-input v-model="addFrom.username"></el-input>
        </el-form-item>
        <!-- 用户密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="addFrom.password" type="password"></el-input>
        </el-form-item>
        <!-- 用户邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addFrom.email"></el-input>
        </el-form-item>
        <!-- 用户手机 -->
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addFrom.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改按钮对话宽 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @closed="editclosed"
    >
      <el-form
        :model="editForm"
        :rules="editrules"
        ref="editruleForm"
        label-width="70px"
      >
        <!-- 用户名 -->
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <!-- 手机 -->
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRoledialogVisible"
      width="50%"
      @close="setClose"
    >
      <div>
        <p>当前的用户:{{ userInfo.username }}</p>
        <p>当前的角色:{{ userInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱
    const checkEmail = (rule, val, cb) => {
      // 验证表单表达式
      const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (regEmail.test(val)) {
        // console.log(regEmail.test(val))
        //合法邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号码
    const checkMobile = (rule, val, cb) => {
      // 验证表单表达式
      const regEmail = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      if (regEmail.test(val)) {
        //合法邮箱
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      // 分配对话框
      setRoledialogVisible: false,
      // 需要分配的角色用户信息
      userInfo: {},
      // 所有角色的列表数据
      rolesList: [],
      // 以选中的id值
      selectedRoleId: '',
      // 修改对话宽
      editDialogVisible: false,
      // 查询到用户信息对象
      editForm: {},
      // 修改表单的验证规则对象
      editrules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制对话框
      addDialogVisible: false,
      total: 0,
      userlist: [],
      params: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 添加用户表单数据
      addFrom: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 表单验证
      rules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    getUserList() {
      this.$axios({
        method: 'get',
        url: 'users',
        params: this.params
      }).then(res => {
        let { data } = res.data
        if (res.data.meta.status !== 200)
          return this.$message.error('获取用户列表失败')
        this.total = data.total
        this.userlist = data.users
        // console.log(data.users)
      })
    },
    // 每页条数改变触发
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.params.pagesize = newSize
      this.getUserList()
    },
    // 单前页触发
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.params.pagenum = newPage
      this.getUserList()
    },
    // 监听switch
    async changeFn(userinfo) {
      console.log(userinfo.mg_state)
      const { data: res } = await this.$axios.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      console.log(res)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return alert('修改用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 监听对话宽关闭事件
    addDialogClosed() {
      // resetFields()将表单重置
      this.$refs.addFromRef.resetFields()
    },
    // 点击按钮，添加新用户
    addUser() {
      this.$refs.addFromRef.validate(val => {
        // 可以发起添加用户的网络
        // console.log(val)
        if (!val) return
        this.$axios({
          method: 'post',
          url: 'users',
          data: this.addFrom
        }).then(res => {
          console.log(res)
          if (res.data.meta.status !== 201)
            return this.$message.error('添加用户失败')
        })

        this.$message.success('添加用户成功')
        // 让单前的款隐藏
        this.addDialogVisible = false
        // 重新获取用户数据
        this.getUserList()
      })
    },
    // 点击修改按钮
    async edit(id) {
      console.log(id)
      this.editDialogVisible = true
      const { data: res } = await this.$axios.get('users/' + id)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('查询失败')
      this.editForm = res.data
    },
    // 监听dialog关闭回调
    editclosed() {
      this.$refs.editruleForm.resetFields()
    },
    // 点击确定  表单预验证
    editUserInfo() {
      this.$refs.editruleForm.validate(async val => {
        if (!val) return
        //发起修改数据请求
        const res = (
          await this.$axios.put('users/' + this.editForm.id, {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          })
        ).data
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        //  关闭面板
        this.editDialogVisible = false
        // 刷新数据
        this.getUserList()
        this.$message.success('修改成功')
      })
    },
    // 点击删除，提示是否确认删除
    async editremove(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 如果点击取消  则返回的是cancel
      //点击确认  返回confirm
      // console.log(confirmResult)
      if (confirmResult == 'cancel') return this.$message.info('以取消删除')

      const { data: res } = await this.$axios.delete('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      // 刷新数据
      this.getUserList()
    },
    // 点击分配按钮
    async setRoled(val) {
      this.userInfo = val
      // console.log(this.userInfo)
      this.setRoledialogVisible = true
      const { data: res } = await this.$axios.get('roles')
      if (res.meta.status !== 200) this.$message.error('获取失败')
      this.$message.success('获取成功')
      this.rolesList = res.data
      // console.log(this.rolesList)
    },
    // 修改用户角色
    async setRoleInfo() {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色')
      }
      console.log(this.selectedRoleId)
      const { data: res } = await this.$axios.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.selectedRoleId
        }
      )
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('分配用户失败')
      this.$message.success('设置角色成功')
      // 刷新数据
      this.getUserList()
      this.setRoledialogVisible = false
    },
    // 监听模态框关闭清空
    setClose() {
      this.userInfo = {}
      this.selectedRoleId = ''
    }
  }
}
</script>

<style></style>
